package com.example.week02.day1.Activity;

import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.example.week02.R;

//计算器简单实现
public class caculator_layout extends AppCompatActivity {

    private EditText etInput;
    private String currentInput = "";
    private double result = 0;
    private String operator = "";
    private boolean resetInput = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.caculator_layout);

        etInput = findViewById(R.id.et_input);
        setupButtonListeners();
    }

    private void setupButtonListeners() {
        // 数字按钮
        int[] numberIds = {
                R.id.tv_0, R.id.tv_1, R.id.tv_2, R.id.tv_3, R.id.tv_4,
                R.id.tv_5, R.id.tv_6, R.id.tv_7, R.id.tv_8, R.id.tv_9
        };

        for (int id : numberIds) {
            findViewById(id).setOnClickListener(v -> appendNumber(((TextView) v).getText().toString()));
        }

        // 运算符按钮
        findViewById(R.id.tv_add).setOnClickListener(v -> setOperator("+"));
        findViewById(R.id.tv_subtract).setOnClickListener(v -> setOperator("-"));
        findViewById(R.id.tv_multiply).setOnClickListener(v -> setOperator("×"));
        findViewById(R.id.tv_divide).setOnClickListener(v -> setOperator("÷"));
        findViewById(R.id.tv_percent).setOnClickListener(v -> setOperator("%"));

        // 功能按钮
        findViewById(R.id.tv_dot).setOnClickListener(v -> appendDecimal());
        findViewById(R.id.tv_equal).setOnClickListener(v -> calculateResult());
        findViewById(R.id.tv_clear).setOnClickListener(v -> clearInput());
        findViewById(R.id.tv_sign).setOnClickListener(v -> toggleSign());

    }

    private void appendNumber(String number) {
        if (resetInput) {
            currentInput = "";
            resetInput = false;
        }

        // 防止多次输入0开头
        if (currentInput.equals("0")) {
            currentInput = number;
        } else {
            currentInput += number;
        }

        etInput.setText(currentInput);
    }

    private void appendDecimal() {
        if (resetInput) {
            currentInput = "0.";
            resetInput = false;
        } else if (!currentInput.contains(".")) {
            if (currentInput.isEmpty()) {
                currentInput = "0.";
            } else {
                currentInput += ".";
            }
        }
        etInput.setText(currentInput);
    }

    private void setOperator(String op) {
        if (!currentInput.isEmpty()) {
            result = Double.parseDouble(currentInput);
        }
        operator = op;
        resetInput = true;
    }

    private void calculateResult() {
        if (operator.isEmpty() || currentInput.isEmpty()) return;

        double inputValue = Double.parseDouble(currentInput);
        switch (operator) {
            case "+":
                result += inputValue;
                break;
            case "-":
                result -= inputValue;
                break;
            case "×":
                result *= inputValue;
                break;
            case "%":
                if (inputValue != 0) {
                    // 使用Java的求余运算（符号与被除数一致）
                    result %= inputValue;
                } else {
                    etInput.setText("Error");
                    resetInput = true;
                    operator = "";
                    return;
                }
                break;
            case "÷":
                if (inputValue != 0) {
                    result /= inputValue;
                } else {
                    etInput.setText("Error");
                    resetInput = true;
                    operator = "";
                    return;
                }
                break;
        }

        // 格式化显示结果
        if (result == (long) result) {
            etInput.setText(String.valueOf((long) result));
        } else {
            etInput.setText(String.valueOf(result));
        }

        currentInput = "";
        operator = "";
        resetInput = true;
    }

    private void clearInput() {
        currentInput = "";
        result = 0;
        operator = "";
        etInput.setText("0");
        resetInput = false;
    }

    private void toggleSign() {
        if (!currentInput.isEmpty() && !currentInput.equals("0")) {
            if (currentInput.startsWith("-")) {
                currentInput = currentInput.substring(1);
            } else {
                currentInput = "-" + currentInput;
            }
            etInput.setText(currentInput);
        } else if (etInput.getText().toString().equals("0")) {
            etInput.setText("-0");
        }
    }

    private void applyPercent() {
        if (!currentInput.isEmpty()) {
            try {
                double value = Double.parseDouble(currentInput);
                // 处理负数的取余（符号与被除数一致）
                double remainder = Math.abs(value) % 100;
                if (value < 0) remainder = -remainder;

                // 格式化显示
                if (remainder == (long) remainder) {
                    currentInput = String.valueOf((long) remainder);
                } else {
                    currentInput = String.valueOf(remainder);
                }
                etInput.setText(currentInput);

                // 关键修复：重置输入状态
                resetInput = true;
            } catch (NumberFormatException e) {
                etInput.setText("Error");
                resetInput = true;
            }
        }
    }
}